import { Box2, Vector2 } from "three";
import NodeLink from "./meta/NodeLink";

/** 边界模糊的 就放这吧*/
export default class MathUtil {

    /** 是否顺时针序
     *  假定p已经是按顺序的点组
     *  
    */
    static toAntiClockWise(p: Array<Vector2>) {
        if ((p ?? []).length < 3) {
            return [];
        }

        //三角有向面积和
        let ts = 0;
        for (let i: number = 0, j = p.length - 1; i < p.length; i++) {

            let pre = p[j];
            let next = p[i];

            ts += pre.cross(next);

            j = i;
        }

        //小于0 是顺时针 大于0是逆时针
        if (ts < 0) {
            p.reverse();
        }
    }



   /**
   * @param p 获取矩形的极值 (AABB包围盒)
   * @returns 
   */
    static getExtremesBox(p: Array<Vector2>): Box2 {
        if (!p) { return null }

        let min: Vector2 = new Vector2(Infinity, Infinity);
        let max: Vector2 = new Vector2(-Infinity, -Infinity);

        for (let v of p) {
            min.min(v);
            max.max(v);
        }

        return new Box2(min, max);
    }


    /**
   * @param p 获取矩形的极值 (AABB包围盒)
   * @returns 
   */
     static getExtremesBox2(n: NodeLink): Box2 {
        if (!n) { return null }

        let min: Vector2 = new Vector2(Infinity, Infinity);
        let max: Vector2 = new Vector2(-Infinity, -Infinity);

        let curr = n;
        do{
            min.min(curr.node);
            max.max(curr.node);
            curr = curr.next;
        }
        while(curr != n);

        return new Box2(min, max);
    }
}